package com.heima.comment.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.heima.comment.service.CommentHotService;
import com.heima.model.comment.pojos.ApComment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author lo
 */
@Service
@Slf4j
public class CommentHotServiceImpl implements CommentHotService {
    @Autowired
    MongoTemplate mongoTemplate;



    /**
     * 处理热点评论
     * @param apComment 评论信息
     */
    @Async("taskExecutor")//指定线程池异步处理请求
    @Override
    public void hotCommentExecutor(ApComment apComment) {
        log.info("异步计算热点文章==================> 开始");

        //1.一个文章最多有5条热点评论
        //查询所有的热点评论
        List<ApComment> apCommentList = mongoTemplate.
                find(Query.query(Criteria.where("articleId").is(apComment.getArticleId()).
                        and("flag").is((short) 1)).with(Sort.by(Sort.Direction.DESC, "likes")), ApComment.class);
        if (CollectionUtils.isEmpty(apCommentList) ||apCommentList.size() < 5) {
            //2.如果某一条评论点赞数超过10就可以把它作为热点评论
            if (apComment.getLikes() > 10) {
                apComment.setFlag((short) 1);
                mongoTemplate.save(apComment);
                return;
            }
        }
        //获取集合的最后一个评论
        ApComment comment = apCommentList.get(apCommentList.size() - 1);
        if (comment.getLikes() < apComment.getLikes()) {
            comment.setFlag((short) 0);
            mongoTemplate.save(comment);
            apComment.setFlag((short) 1);
            mongoTemplate.save(apComment);
        }
        log.info("异步计算热点文章==================> 结束");
    }


}
